import { onMounted, reactive, ref, watch } from 'vue';
import { page } from '@/services';

export default function usePage(url, searchFormState = {}) {
  const tableData = ref([]);
  const loading = ref(false);
  const current = ref(1);
  const pageSize = ref(20);
  const total = ref(0);
  const searchForm = ref(null);

  const pagination = reactive({
    current: current,
    total: total,
    pageSize: pageSize,
    showSizeChanger: true,
    showQuickJumper: true,
    onChange: (_page, _pageSize) => {
      current.value = _page;
    },
    onShowSizeChange: (_current, _pageSize) => {
      current.value = 1;
      pageSize.value = _pageSize;
    },
  });

  const search = async () => {
    if (!url) return;
    loading.value = true;
    const params = { current: current.value, pageSize: pageSize.value, data: searchFormState };

    const res = await page(`/api/${url}`, params);
    const { success, page: pageData } = res;
    if (success) {
      const { list: listData, total: totalData } = pageData;

      tableData.value = listData;
      total.value = Number(totalData);
    }

    loading.value = false;
  };

  watch(current, search);
  watch(pageSize, search);

  onMounted(async () => {
    await search();
  });

  const restSearchForm = () => {
    searchForm.value.resetFields();
    console.log('restSearchForm');
  };

  return {
    tableData,
    pagination,
    loading,

    search,
    searchForm,
    restSearchForm,
  };
}
